import numpy as np    
import matplotlib.pyplot as plt    
from PIL import Image    
  
# 打开图像并转换为NumPy数组    
image1 = Image.open("C:\\Users\\lenovo\\Desktop\\Math\\1.jpg").convert('RGB')    
image1_array = np.array(image1)    
  
image2 = Image.open("C:\\Users\\lenovo\\Desktop\\Math\\2.jpg").convert('RGB')    
image2_array = np.array(image2)    
  
# 确保两张图像的尺寸相同    
assert image1_array.shape == image2_array.shape, "图像必须有相同的尺寸"    
  
# 矩阵加法运算    
added_image_array = image1_array + image2_array    
added_image_array = np.clip(added_image_array, 0, 255).astype(np.uint8)  
  
# 矩阵减法运算    
subtracted_image_array = image1_array - image2_array    
subtracted_image_array = np.clip(subtracted_image_array, 0, 255).astype(np.uint8)  
  
# 矩阵乘法运算      
multiplied_image_array = image1_array * image2_array / 255.0  # 先除以255避免溢出，再乘以对方数组  
multiplied_image_array = np.clip(multiplied_image_array * 255, 0, 255).astype(np.uint8)  # 再乘回255并裁剪  
  
# 矩阵除法运算     
divisor = np.where(image2_array == 0, 1, image2_array)  # 避免除以零，将零替换为1  
divided_image_array = image1_array.astype(np.float32) / divisor  # 转换为浮点型进行除法  
divided_image_array = np.clip(divided_image_array * 255 / np.max(divided_image_array), 0, 255).astype(np.uint8)  # 缩放到0-255

# 显示原始图像和处理后的图像    
fig, axes = plt.subplots(1, 5, figsize=(20, 5))  
  
axes[0].imshow(image1_array)    
axes[0].set_title('Original Image 1')    
axes[0].axis('off')    
  
axes[1].imshow(added_image_array)    
axes[1].set_title('Added Image')    
axes[1].axis('off')    
  
axes[2].imshow(subtracted_image_array)    
axes[2].set_title('Subtracted Image')    
axes[2].axis('off')    
  
axes[3].imshow(multiplied_image_array)    
axes[3].set_title('Multiplied Image')    
axes[3].axis('off')    
  
axes[4].imshow(divided_image_array)    
axes[4].set_title('Divided Image')    
axes[4].axis('off')    
  
plt.show()
